#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
@Author   : long.hai
@Contact  : 1982964634@qq.com
@Command  : 操控页面，执行页面动作
"""
import time
from _base.base import BasePage
from _step.config import Config
from _step.send_msg import SendMsg
from _step.step import Step
import traceback


class DrivePage(Config, SendMsg):

    def __init__(self, base_page):
        self.base_page: BasePage = base_page
        Config.__init__(self, base_page)
        SendMsg.__init__(self, base_page)

    async def before(self, step: Step):
        """
        调用playwright对象操作页面
        :param step: 步骤数据
        :return:
        """
        # 获取步骤uuid和配置中的执行后截图截图
        uuid = step.uuid
        after_screenshot = step.config.after_screenshot
        # 重置步骤日志、截图
        self.base_page.log_text = ""
        self.base_page.image_urls = []
        # 获取用例每一步的开始执行时间
        step_start_time = time.time()
        # 步骤执行状态：1.成功 2.失败 3.进行中 4.跳过
        step_run_status = 1
        try:
            await self.send_rate(uuid, 20)
            await self.after(step)
        except Exception as e:
            step_run_status = 2  # 设置状态为失败
            # await my_playwright.screenshot()  # 执行异常截图
            raise e
        finally:
            # 执行完成截图
            await self.after_screenshot(after_screenshot)
            # 获取用例步骤执行耗时
            step_use_time = round((time.time() - step_start_time) * 1000)
            await self.send_rate(uuid, 100)
            await self.base_page.collect_step_report(step.name, step_run_status, step_use_time)

    # 加载测试步骤数据后调用my_playwright执行操作

    async def after(self, step: Step):
        try:
            uuid = step.uuid
            await self.send_rate(uuid, 40)
            # 存在变量引用符号，则调用方法替换变量
            # print(repr(step.locators))

            params = self.base_page.re_replace_variable(step.params)
            result = self.base_page.re_replace_variable(step.result)
            # 加载测试步骤数据
            kwargs = {"locators": step.locators, "params": params, "result": result}
            method = step.action.method
            await self.send_rate(uuid, 60)
            # 页面操作控制
            # action_need_keys = ['method', 'is_element', 'is_params', 'is_return']
            # method, is_element, is_params, is_return = [action_dict[key] for key in keys_to_get]

            # 调用Playwright对象操作页面
            await getattr(self.base_page, method)(**kwargs)  # 无元素-有参数-有返回值
            await self.send_rate(uuid, 80)
        except Exception as e:
            raise e
